<?php

namespace App\Http\Controllers;

use App\Article;
use App\Episode;
use App\Image;
use App\Jobs\GetShowDetail;
use App\Movie;
use App\Show;
use App\Vote;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;

class ShowController extends Controller
{
    protected $bucketMgr;

    public function __construct()
    {
        $this->middleware(['auth', 'admin'], ['except' => ['hotShows', 'show', 'latestInWallShow', 'latestOutWallShow', 'textDetail']]);
        $accessKey = config('app.QN_accessKey');
        $secretKey = config('app.QN_secretKey');
        $this->bucketMgr = new BucketManager(new Auth($accessKey, $secretKey));
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {


        //       $shows = Show::has('images','<',1)->paginate(10);
        $shows = Show::orderBy('name_en')->paginate(90);


        $showList = Show::orderBy('name_en')->pluck('name_en', 'id');


        return view('show.index', compact('shows', 'showList'));
    }

    public function hotShows()
    {

        $yesterday = Carbon::now()->subHour(36);
        $shows = Show::where('updated_at', '>', $yesterday)->orderBy('updated_at', 'desc')->paginate(21);
        $shows->load(['vote' => function ($voteQ) {
            $voteQ->orderBy('score', 'desc');
        }]);

        $title = '每日最新美剧下载资源';
        $keyWord = '最新美剧资源';
        $description = '';

        $count = 0;
        foreach ($shows as $show) {
            $count++;
            $keyWord .= $show->name_en . ',';
            $description .= $show->name_zh . $show->name_en . ',';
            if ($count > 8) {
                break;
            }
        }
        return view('web.hotShows', compact('shows', 'title', 'keyWord', 'description'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('show.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $name_en = $request->input('name_en');
        $name_en = str_ireplace('.', ' ', $name_en);
        $name_en = trim($name_en);
        $show = Show::firstOrCreate(['name_en' => $name_en]);
        return redirect(route('show.edit', $show));
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show(Show $show)
    {
        $vote = Vote::where('show_id', '=', $show->id)->first();
        if ($vote) {
            $vote->increment('visit');
        } else {
            $vote = new Vote(['visit' => 1]);
            $vote->show_id = $show->id;
            $vote->save();
        }
        $shows = Show::where('updated_at', '>', Carbon::now()->subHour(24))->orderBy('updated_at', 'desc')->get();
        return view('show.detail', compact('show', 'shows'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Show $show)

    {
        $articles = Article::all()->pluck('title', 'id')->toArray();
        return view('show.edit', compact('show', 'articles'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Show $show)
    {
        $job = new GetShowDetail($show);
        $this->dispatch($job->delay(1));


        $show->update($request->all());
        $page_image_url = $request->input('page_image');
        if (str_contains($page_image_url, ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'png', 'tiff'])) {
            $show->page_image = $page_image_url;
        }
        $show->save();
        if ($show->vote) {
            $show->vote->score = $request->input('score');
            $show->vote->save();
        }

//        dd($show->images->toArray());


        //图片只增加不删除
        $imageUrls = $show->images()->pluck('fname');//数据库中的url collection

        $inputUrls = $request->input('url_list');//表单url array
        $collection = collect($inputUrls);
        $urlsToBeAdded = $collection->diff($imageUrls);//要添增加的图片url
//        dd($urlsToBeAddeded,$collection,$inputUrls);
        foreach ($urlsToBeAdded as $url) {
            if (str_contains($url, ['jpg', 'png', 'jpeg', 'gif', 'bmp', 'png', 'tiff'])) {
                $key = 'web_show_' . uniqid();
                $alt = $show->full_name;
                $image = Image::fetchUrlWithKey($url, $key, $alt);
                $show->images()->save($image);
            }
        }

        return redirect(route('show.edit', $show));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function fetchImageBy($url, $key)
    {
        $alt = 'web_url' . date('ymdhis');
        $image = Image::fetchUrlWithKey($url, $key, $alt);
        return response()->json($image);
    }

    public function latestInWallShow()
    {
        $shows = Show::whereHas('episodes', function ($query) {
            $query->where('provider', 'like', '%ttmj%')->orWhere('provider', 'like', '%yyets%')
                ->where('updated_at', '>', Carbon::now()->subHour(12));
        })->has('episodes', '>', 0)
            ->orderBy('updated_at', 'desc')->paginate(18);

        $title = '国内最新美剧下载资源';
        $keyWord = '';
        $description = '';
        $count = 0;
        foreach ($shows as $show) {
            $count++;
            $keyWord .= $show->name_en . ',';
            $description .= $show->name_zh . $show->name_en . ',';
            if ($count > 8) {
                break;
            }
        }
        return view('web.hotShows', compact('shows', 'title', 'keyWord', 'description'));
    }

    public function latestOutWallShow()
    {
        $shows = Show::whereHas('episodes', function ($query) {
            $query->where('provider', 'like', '%eztv%')
                ->where('updated_at', '>', Carbon::now()->subHour(12));
        })->has('episodes', '>', 0)
            ->orderBy('updated_at', 'desc')->paginate(18);

        $title = '国内最新美剧下载资源';
        $keyWord = '';
        $description = '';
        $count = 0;
        foreach ($shows as $show) {
            $count++;
            $keyWord .= $show->name_en . ',';
            $description .= $show->name_zh . $show->name_en . ',';
            if ($count > 8) {
                break;
            }
        }
        return view('web.hotShows', compact('shows', 'title', 'keyWord', 'description'));
    }

    public function textDetail(Show $show)
    {
        return view('show.detailText', compact('show'));
    }


    public function swapShow(Show $show)
    {
        $show_list = Show::all()->pluck('name_en', 'id');
        $ep_list = $show->episodes()->orderby('raw_name', 'desc')->limit(500)->pluck('raw_name', 'id');
        return view('show.swapEpisode', compact('ep_list', 'show_list', 'show'));
    }

    public function swapShowUpdate(Request $request)
    {
        foreach ($request->input('episodeIds') as $item) {
            $ep = Episode::find($item);
            $ep->show_id = $request->input('showId');
            $ep->save();
        }

        return redirect(url('show'));
    }

    public function nameOfShow(Request $request)
    {
        $showId = $request->input('showName');
        $show = Show::find($showId);
        return redirect(url('show', $show));

    }

    public function cloneShow(Show $fromShow, Show $toShow)
    {


    }

    public function recentlyUpdatedShows()
    {
        $shows = Cache::get('recentlyUpdatedShows');
        if (!$shows) {
            $shows = Show::whereHas('episodes', function ($query) {
                $query->where('updated_at', '>', Carbon::now()->subHour(48));
            })->has('episodes', '>', 0)
                ->orderBy('updated_at', 'desc')->get();

            Cache::put('recentlyUpdatedShows', $shows, 10);
        }
        $title = '国内最近更新美剧下载资源';
        $keyWord = '';
        $description = '';
        $count = 0;
        foreach ($shows as $show) {
            $count++;
            $keyWord .= $show->name_en . ',';
            $description .= $show->name_zh . $show->name_en . ',';
            if ($count > 8) {
                break;
            }
        }
        return view('show.recentlyUpdatedShows', compact('shows', 'title', 'keyWord', 'description'));

    }


    public function createShowWithEpisode(Request $request)
    {
        $show_name = $request->input('showName');
        $show_name = preg_replace('#\W+#', ' ', $show_name);
        $show_name = trim($show_name);
        if (strlen($show_name) < 3) {
            return '不能为空';
        }
        $show = Show::firstOrCreate(['name_en' => $show_name]);

        $keyword = str_replace(' ', '%', $show_name);
        $keyword = '%' . $keyword . '%';

        $epIDs = Episode::where('show_id', '=', 396)->where('raw_name', 'like', $keyword)->get()->pluck(['id']);
        foreach ($epIDs as $item) {

            $ep = Episode::find($item);
            $ep->show_id = $show->id;
            $ep->timestamps = false;
            $ep->save();
        }
        return redirect('/swapShow/396');
    }

    public function createMovieWithEpisode(Request $request)
    {


        $movieName = $request->input('movieName');
        $movieName = preg_replace('#\W+#', ' ', $movieName);
        $movieName = trim($movieName);
        if (strlen($movieName) < 3) {
            return '不能为空';
        }
        $movie = Movie::firstOrCreate(['name_en' => $movieName]);

        $keyword = str_replace(' ', '%', $movieName);
        $keyword = '%' . $keyword . '%';

        $epIDs = Episode::where('show_id', '=', 396)->where('raw_name', 'like', $keyword)->get()->pluck(['id']);
        foreach ($epIDs as $item) {
            $ep = Episode::find($item);
            $ep->show_id = null;
            $ep->movie_id = $movie->id;
            $ep->save();
        }
        return redirect('/swapShow/396');
    }


}
